Python - tutorial - 02/14

data types - number - string

Revision:


Python - data types

Built-in data types:

Variables can store data of different types, and different types can do different things. Python has the following data types built-in by defaults:

Text type : str
Numeric types : int, float, complex
Sequence types : list, tuple, range
mapping type : dict
Set types : set, frozenset
Boolean type : bool
Binary types : bytes, bytearray, memoryview

Getting the data type: get the data type of any object by using the type() function.

Example 1: print the data type of the variable x:

        x = 5
        print(type(x))  # class 'int'
    

Setting the data type: in Python, the data type is set when you assign a value to a variable.

Example 2: set the data type

        x = "Hello World"	# str	
        x = 20	# int	
        x = 20.5	# float	
        x = 1j	# complex	
        x = ["apple", "banana", "cherry"]   # list	
        x = ("apple", "banana", "cherry")	# tuple	
        x = range(6)	# range	
        x = {"name" : "John", "age" : 36}	# dict	
        x = {"apple", "banana", "cherry"}	# set	
        x = frozenset({"apple", "banana", "cherry"})	# frozenset	
        x = True	# bool	
        x = b"Hello"	# bytes	
        x = bytearray(5)	# bytearray	
        x = memoryview(bytes(5))	# memoryview
    

Setting the specific data type: if you want to specify the data type, you can use the following constructor functions:

Example 3: set the specific data type

        x = str("Hello World")	# str	
        x = int(20)	# int	
        x = float(20.5)	# float	
        x = complex(1j)	# complex	
        x = list(("apple", "banana", "cherry"))	# list	
        x = tuple(("apple", "banana", "cherry"))	# tuple	
        x = range(6)	# range	
        x = dict(name="John", age=36)	# dict	
        x = set(("apple", "banana", "cherry"))	# set	
        x = frozenset(("apple", "banana", "cherry"))	# frozenset	
        x = bool(5)	# bool	
        x = bytes(5)	# bytes	
        x = bytearray(5) 	# bytearray	
        x = memoryview(bytes(5))	# memoryview
    


Python - numbers

There are three numeric types in Python: int, float, complex.

Variables of numeric types are created when you assign a value to them.

Example 4:

        x = 1    # int
        y = 2.8  # float
        z = 1j   # complex
    

To verify the type of any object in Python, use the type() function:

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

Example 5: integers

        x = 1
        y = 35656222554887711
        z = -3255522
        print(type(x)) # class 'int'
        print(type(y)) # class 'int'
        print(type(z)) # class 'int'   
    

Float, or "floating point number" is a number, positive or negative, containing one or more decimals.

Example 6: floats

        x = 1.10
        y = 1.0
        z = -35.59
        print(type(x)) # class 'float'
        print(type(y)) # class 'float'
        print(type(z)) # class 'float'
    

Float can also be scientific numbers with an "e" to indicate the power of 10.

Example 7: scientific numbers are floats

        x = 35e3
        y = 12E4
        z = -87.7e100
        print(type(x)) # class 'float'
        print(type(y)) # class 'float'
        print(type(z)) # class 'float'
    

Complex numbers are written with a "j" as the imaginary part.

Example 8: complex numbers

        x = 3+5j
        y = 5j
        z = -5j
        print(type(x)) # class 'complex'
        print(type(y)) # class 'complex'
        print(type(z)) # class 'complex'
    

Type conversion:

You can convert from one type to another with the int(), float(), and complex() methods.

Example 9: convert from one type to another:

        x = 1    # int
        y = 2.8  # float
        z = 1j   # complex

        #convert from int to float: a = float(x)
        #convert from float to int: b = int(y)
        #convert from int to complex: c = complex(x)

        print(a)  # 1.0
        print(b)  # 2
        print(c)  # (1+0j)

        print(type(a)) # class 'float'
        print(type(b)) # class 'int'
        print(type(c)) # class 'complex'
    

Note: you cannot convert complex numbers into another number type.

Random number:

Python does NOT have a random() function to make a random number, but Python has a built-in module called "random" that can be used to make random numbers.

Example 10: import the random module, and display a random number between 1 and 9:

        import random
        print(random.randrange(1, 10)) # 3
    


Python - casting

Specifying a variable type can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types. Casting in python is therefore done using constructor functions:

int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number);
float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer);
str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals.

Example 11: integers

        x = int(1)   # x will be 1
        y = int(2.8) # y will be 2
        z = int("3") # z will be 3
    

Example 12: floats

        x = float(1)     # x will be 1.0
        y = float(2.8)   # y will be 2.8
        z = float("3")   # z will be 3.0
        w = float("4.2") # w will be 4.2
    

Example 13: strings

        x = str("s1") # x will be 's1'
        y = str(2)    # y will be '2'
        z = str(3.0)  # z will be '3.0'
    


Python - strings

Strings in Python are surrounded by either single quotation marks, or double quotation marks.

'hello' is the same as "hello".
A string literal vcan be displayed with the print() function.

Assigning a string to a variable is done with the variable name followed by an equal sign and the string.

Example 14:

        a = "Hello"
        print(a) # Hello
    

Multiline strings can be assigned to a variable by using three double quotes or three single quotes.

Example 15: three double quotes

        a = """Lorem ipsum dolor sit amet,
        consectetur adipiscing elit,
        sed do eiusmod tempor incididunt
        ut labore et dolore magna aliqua."""
        print(a)
    

Example 16: three single quotes

        a = '''Lorem ipsum dolor sit amet,
        consectetur adipiscing elit,
        sed do eiusmod tempor incididunt
        ut labore et dolore magna aliqua.'''
        print(a)
    

Strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type. A single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.

Example 17: Get the character at position 1 (remember that the first character has the position 0):

        a = "Hello, World!"
        print(a[1]) # e
    

Looping through the characters in a string with a for loop can be done, since strings are arrays.

Example 18: loop through the letters in the word "banana":

        for x in "banana":
        print(x) # b a n a n a
    

Length of a string: can be obtained by using the len() function.

Example 19: the len() function returns the length of a string

        a = "Hello, World!"
        print(len(a)) # 13
    

Check string: to check if a certain phrase or character is present in a string, we can use the keyword "in".

Example 20: check if "free" is present in the following text:

        txt = "The best things in life are free!"
        print("free" in txt) # True
    

Use it in an "if" statement

Example 21: print only if "free" is present:

        txt = "The best things in life are free!"
        if "free" in txt:
        print("Yes, 'free' is present.") # Yes, 'free' is present.
    

Check if NOT: to check if a certain phrase or character is NOT present in a string, we can use the keyword "not in".

Example 22: check if "expensive" is NOT present in the following text:

        txt = "The best things in life are free!"
        print("expensive" not in txt) # True
    

Use it in an "if" statement

Example 23: print only if "expensive" is NOT present:

        txt = "The best things in life are free!"
        if "expensive" not in txt:
            print("Yes, 'expensive' is NOT present.") # Yes, 'expensive' is NOT present.
    

Slicing strings allows to return a part of a string

A range of characters can be returned by using the slice syntax: specify the start index and the end index, separated by a colon.

Example 24: get the characters from position 2 to position 5 (not included):

        b = "Hello, World!"
        print(b[2:5])  # llo
    

Slice from the start by leaving out the start index; the range will start at the first character.

Example 25: set the characters from the start to position 5 (not included):

        b = "Hello, World!"
        print(b[:5]) # Hello
     

Slice to the end: by leaving out the end index, the range will go to the end:

Example 26: get the characters from position 2, and all the way to the end:

        b = "Hello, World!"
        print(b[2:]) # llo, World!
    

Negative indexing: use negative indexes to start the slice from the end of the string.

Example 27: get the characters: from: "o" in "World!" (position -5) to, but not included: "d" in "World!" (position -2):

        b = "Hello, World!"
        print(b[-5:-2])  # orl
    

Modify strings

Upper case: the upper() method returns the string in upper case.

Example 28: the upper() method:

        a = "Hello, World!"
        print(a.upper()) # HELLO, WORLD!
    

Lower case: the lower() method returns the string in lower case.

Example 29: the lower() method

        a = "Hello, World!"
        print(a.lower()) # hello, world!
    

Remove whitespace: Whitespace is the space before and/or after the actual text, and very often you want to remove this space. The strip() method removes any whitespace from the beginning or the end:

Example 30: the strip() method

        a = " Hello, World! "
        print(a.strip()) # returns "Hello, World!"
    

Replace string: the replace() method replaces a string with another string.

Example 31: the replace() method

        a = "Hello, World!"
        print(a.replace("H", "J")) # Jello, World!
    

Split string: the split() method returns a list where the text between the specified separator becomes the list items.

Example 32: the split() method splits the string into substrings if it finds instances of the separator:

        a = "Hello, World!"
        print(a.split(",")) # returns ['Hello', ' World!']
    

String concatenation

To concatenate, or combine, two strings you can use the "+" operator.

Example 33: merge variable "a" with variable "b" into variable "c":

        a = "Hello"
        b = "World"
        c = a + b
        print(c) # HelloWorld
    

Example 34: to add a space between them, add a " ":

        a = "Hello"
        b = "World"
        c = a + " " + b
        print(c) # Hello World
    

Format strings

String format: in Python, we cannot combine strings and numbers using the "+" operator. But we can combine strings and numbers by using the format() method. The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are.

Example 35: use the format() method to insert numbers into strings:

        age = 36
        txt = "My name is John, and I am {}"
        print(txt.format(age)) # My name is John, and I am 36
    

The format() method takes unlimited number of arguments, and are placed into the respective placeholders.

Example 36: format() method with various arguments:

        quantity = 3
        itemno = 567
        price = 49.95
        myorder = "I want {} pieces of item {} for {} dollars."
        print(myorder.format(quantity, itemno, price)) # I want 3 pieces of item 567 for 49.95 dollars.
    

You can use index numbers {0} to be sure the arguments are placed in the correct placeholders:

Example 37: use index numbers {0}

        quantity = 3
        itemno = 567
        price = 49.95
        myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
        print(myorder.format(quantity, itemno, price)) # I want to pay 49.95 dollars for 3 pieces of item 567
    


Python - string methods

String methods: Python has a set of built-in methods that you can use on strings. All string methods returns new values. They do not change the original string.

Method - Description
capitalize() - converts the first character to upper case
casefold() - converts string into lower case
center() - returns a centered string
count() - returns the number of times a specified value occurs in a string
encode() - returns an encoded version of the string
endswith() - returns true if the string ends with the specified value
expandtabs() - sets the tab size of the string
find() - searches the string for a specified value and returns the position of where it was found
format() - formats specified values in a string
format_map() - formats specified values in a string
index() - searches the string for a specified value and returns the position of where it was found
isalnum() - returns True if all characters in the string are alphanumeric
isalpha() - returns True if all characters in the string are in the alphabet
isdecimal() - returns True if all characters in the string are decimals
isdigit() - returns True if all characters in the string are digits
isidentifier() - returns True if the string is an identifier
islower() - returns True if all characters in the string are lower case
isnumeric() - returns True if all characters in the string are numeric
isprintable() - returns True if all characters in the string are printable
isspace() - returns True if all characters in the string are whitespaces
istitle() - returns True if the string follows the rules of a title
isupper() - returns True if all characters in the string are upper case
join() - joins the elements of an iterable to the end of the string
ljust() - returns a left justified version of the string
lower() - converts a string into lower case
lstrip() - returns a left trim version of the string
maketrans() - returns a translation table to be used in translations
partition() - returns a tuple where the string is parted into three parts
replace() - returns a string where a specified value is replaced with a specified value
rfind() - searches the string for a specified value and returns the last position of where it was found
rindex() - searches the string for a specified value and returns the last position of where it was found
rjust() - returns a right justified version of the string
rpartition() - returns a tuple where the string is parted into three parts
rsplit() - splits the string at the specified separator, and returns a list
rstrip() - returns a right trim version of the string
split( - splits the string at the specified separator, and returns a list
splitlines() - splits the string at line breaks and returns a list
startswith() - returns true if the string starts with the specified value
strip() - returns a trimmed version of the string
swapcase() - swaps cases, lower case becomes upper case and vice versa
title() - converts the first character of each word to upper case
translate() - returns a translated string
upper() - converts a string into upper case
zfill() - fills the string with a specified number of 0 values at the beginning


Python - escape characters

Escape characters: to insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is surrounded by double quotes.

Example 38: you will get an error if you use double quotes inside a string that is surrounded by double quotes:

        txt = "We are the so-called "Vikings" from the north."
    

To fix this problem, use the escape character \":

Example 39: the escape character allows you to use double quotes when you normally would not be allowed:

        txt = "We are the so-called \"Vikings\" from the north."
    

Other escape charascters used in Python:

Code - Result
\' - Single Quote
\\ - Backslash
\n - New Line
\r - Carriage Return
\t - Tab
\b - Backspace
\f - Form Feed
\ooo - Octal value
\xhh - Hex value